package com.fengmi.controller;

import cn.hutool.json.JSONUtil;
import com.fengmi.vo.ResultVO;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * @Author 123
 * @Date 2022/1/25 10:07
 * @Version 1.0
 */

@RestController
@CrossOrigin
@RequestMapping("upload")
public class UploadController {

    @Value("${qiniu.accessKey}")
    private  String accessKey;

    @Value("${qiniu.secretKey}")
    private String secretKey;

    @Value("${qiniu.bucket}")
    private String bucket;

    @Value("${qiniu.host}")
    private String HOST;

    @PostMapping("img")
    public ResultVO upload(MultipartFile file) {
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.huanan());
        UploadManager uploadManager = new UploadManager(cfg);
        String key = null;
        try {
            byte[] bytes = file.getBytes();
            Auth auth = Auth.create(accessKey, secretKey);
            String upToken = auth.uploadToken(bucket);
            Response response = uploadManager.put(bytes, key, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = JSONUtil.toBean(response.bodyString(), DefaultPutRet.class);
            System.out.println(putRet.key);
            //System.out.println(putRet.hash);
            return  new ResultVO(true, "success",HOST+putRet.key);
        } catch (Exception ex) {
            return  new ResultVO(false, "error","");
        }
    }
}

